package info.xinfu.carban.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView;
import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.xinfu.carban.Event_Send_Message;
import info.xinfu.carban.R;
import info.xinfu.carban.activity.CarEditActivity;
import info.xinfu.carban.base.BaseFragment;
import info.xinfu.carban.entity.RecordEntity;
import info.xinfu.carban.eparking.KHTSample;
import info.xinfu.carban.event.Event_Play_Camera;
import info.xinfu.carban.myview.MyImageDialog;
import info.xinfu.carban.utils.ACache;
import info.xinfu.carban.utils.Constants;
import info.xinfu.carban.utils.SPUtils;
import info.xinfu.carban.utils.TimeUtil;
import io.realm.Realm;

public class BanFeeRootFragment extends BaseFragment {
    @BindView(R.id.magic_indicator)
    MagicIndicator mIndicator;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    Unbinder unbinder;
    @BindView(R.id.id_include_head_title)
    TextView idIncludeHeadTitle;
    @BindView(R.id.id_include_head_goback)
    RelativeLayout idIncludeHeadGoback;
    @BindView(R.id.id_include_head_right)
    TextView idIncludeHeadRight;
    @BindView(R.id.fillStatusBarView)
    View fillStatusBarView;
    @BindView(R.id.iv_entry)
    ImageView ivEntry;
    @BindView(R.id.iv_exit)
    ImageView ivExit;
    @BindView(R.id.iv_compare)
    ImageView ivCompare;
    @BindView(R.id.tv_car_number)
    TextView tvCarNumber;
    @BindView(R.id.tv_fee_type)
    TextView tvFeeType;
    @BindView(R.id.car_type)
    TextView carType;
    @BindView(R.id.tv_entry_time)
    TextView tvEntryTime;
    @BindView(R.id.tv_exit_time)
    TextView tvExitTime;
    @BindView(R.id.tv_park_time)
    TextView tvParkTime;
    @BindView(R.id.tv_fee_value)
    TextView tvFeeValue;
    @BindView(R.id.tv_charged_value)
    TextView tvChargedValue;
    @BindView(R.id.tv_reduce_value)
    TextView tvReduceValue;
    @BindView(R.id.tv_should_value)
    TextView tvShouldValue;
    @BindView(R.id.tv_sum_value)
    TextView tvSumValue;
    @BindView(R.id.ll_car_info)
    LinearLayout llCarInfo;
    @BindView(R.id.btn_cancel)
    Button btnCancel;
    @BindView(R.id.btn_open)
    Button btnOpen;
    @BindView(R.id.tv_ipconfig)
    TextView tvIpconfig;
    //存放请假类型的map
    private ArrayList<Fragment> mFraList;
    private static final String[] CHANNELS = new String[]{"进车视频", "出车视频"};
    private List<String> tabs = Arrays.asList(CHANNELS);
    BanFeeEntryragment fragment_one;
    BanFeeEntryragment fragment_two;
    List<RecordEntity> recordEntities = new ArrayList<>();

    KHTSample.FuncActivity camer1 = new KHTSample.FuncActivity();
    KHTSample.FuncActivity camer2 = new KHTSample.FuncActivity();
    private String ipentry = "192.168.1.55";
    private String ipexit = "192.168.1.56";
    private GoogleApiClient client;
    private String mType = "";
    Bitmap bitmap;
    Bitmap entrybitmap;
    Bitmap exitbitmap, comparebitmap;
    Realm mRealm;
    public static BanFeeRootFragment getInstance(String type) {
        BanFeeRootFragment fragment1 = new BanFeeRootFragment();
        Bundle bdl = new Bundle();
        bdl.putString("type", type);
        fragment1.setArguments(bdl);
        return fragment1;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        client = new GoogleApiClient.Builder(context).addApi(AppIndex.API).build();
        Realm.init(context);
//        mRealm = Realm.getDefaultInstance();
//        addRecordList();//test data
        initViewPager();
        initIndicator();
        idIncludeHeadTitle.setText("岗亭收费");
        idIncludeHeadGoback.setVisibility(View.GONE);
//        idIncludeHeadRight.setVisibility(View.VISIBLE);
        llCarInfo.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(SPUtils.getString("ipentry", ""))) {
            EventBus.getDefault().post(new Event_Play_Camera(true));
        }


    }

    private void initViewPager() {
        mFraList = new ArrayList<>();

//        fragment_one = RecordHeartFragment.newInstance();
       /* fragment_one = new BanFeeEntryragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString("type", "entry");

        fragment_one.setArguments(bundle1);*/
        fragment_one = BanFeeEntryragment.getInstance("entry");
        fragment_two = BanFeeEntryragment.getInstance("exit");
    /*    Bundle bundle = new Bundle();
        bundle.putString("type", "exit");
        fragment_two.setArguments(bundle);*/
        mFraList.add(fragment_one);
        mFraList.add(fragment_two);

        ManagePagerAdapter pagerAdapter = new ManagePagerAdapter(getActivity().getSupportFragmentManager(), mFraList);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(pagerAdapter);

    }

    private void initIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(context);
        //自适应tab的个数居中,
        // 布局中让在xml里中将MagicIndicator套在Gravity为Center的布局中
        commonNavigator.setAdjustMode(true);
        commonNavigator.setSkimOver(true);
        mIndicator.setBackgroundResource(R.drawable.round_indicator_bg);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabs == null ? 0 : tabs.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ClipPagerTitleView simplePagerTitleView = new ClipPagerTitleView(context);
                simplePagerTitleView.setText(tabs.get(index));
                simplePagerTitleView.setClipColor(Color.WHITE);
                simplePagerTitleView.setTextColor(Color.parseColor("#e94220"));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {

                LinePagerIndicator indicator = new LinePagerIndicator(context);
                float navigatorHeight = context.getResources().getDimension(R.dimen.common_navigator_height);
                float borderWidth = UIUtil.dip2px(context, 1);
                float lineHeight = navigatorHeight - 2 * borderWidth;
                indicator.setLineHeight(lineHeight);
                indicator.setRoundRadius(5);
                indicator.setYOffset(borderWidth);
                indicator.setColors(Color.parseColor("#FF6633"));
                return indicator;
            }
        });
        mIndicator.setNavigator(commonNavigator);

        ViewPagerHelper.bind(mIndicator, mViewPager);
    }

    @OnClick(R.id.id_include_head_right)
    public void onViewClicked() {
        startActivity(CarEditActivity.class);
    }


    private class ManagePagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> mData;


        private ManagePagerAdapter(FragmentManager fm, ArrayList<Fragment> mData) {
            super(fm);
            this.mData = mData;
        }

        @Override
        public Fragment getItem(int position) {

            return mData.get(position);
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }
    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_fee_root;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
//        mRealm.close();
    }
    private void addRecordList(){
        final String uname = SPUtils.getString(Constants.username, "");
        recordEntities = JSON.parseArray(mCache.getAsString(uname),RecordEntity.class);
        RecordEntity recordEntity = new RecordEntity();
        recordEntity.setOperatorName(uname);
        recordEntity.setCardNo(tvCarNumber.getText().toString());
        Date now = new Date();
        recordEntity.setCreateTime(now.getTime());
        recordEntities.add(recordEntity);
        String points = JSON.toJSONString(recordEntities);
        mCache.put(uname,points);
        EventBus.getDefault().post(new Event_Send_Message(true));
        showToast("开闸成功");
     /*   mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RecordEntity recordEntity = realm.createObject(RecordEntity.class);
                recordEntity.setCardNo("test");//tvCarNumber.getText().toString()
                recordEntity.setName(uname);
                Date now = new Date();
                recordEntity.setCreateTime(now.getTime());
            }
        });*/

    }
    @OnClick({R.id.btn_cancel, R.id.btn_open, R.id.tv_ipconfig, R.id.iv_entry,
            R.id.iv_exit, R.id.iv_compare})
    public void onViewClicked(View view) {
        MyImageDialog myImageDialog;
        int screenWidth = context.getWindowManager().getDefaultDisplay().getWidth();
        int screenHeight = context.getWindowManager().getDefaultDisplay().getHeight();
        switch (view.getId()) {
//            ShowOriginPicActivity.navigateTo((Activity) context,avatarUrl);
            case R.id.iv_entry:
                if(entrybitmap!=null){
                    myImageDialog = new MyImageDialog(getActivity(), 0, 0, 0, entrybitmap);
                    myImageDialog.show();
                } else {
                    Trigger_Button();
                }

                break;
            case R.id.iv_exit:
                if(exitbitmap!=null){
                    myImageDialog = new MyImageDialog(getActivity(), 0, 0, 0, exitbitmap);
                    myImageDialog.show();
                } else {
                    Trigger_Button2();
                }

                break;
            case R.id.iv_compare:
                myImageDialog = new MyImageDialog(getActivity(), 0, 0, 0, comparebitmap);
                myImageDialog.show();

                break;
            case R.id.btn_cancel:
                break;
            case R.id.btn_open:
                if (TextUtils.equals(mType, "entry")) {
                    UP_Button();
                } else {
                    UP_Button2();
                }

                break;
            case R.id.tv_ipconfig:
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                View dialog_ll = View
                        .inflate(getActivity(), R.layout.dialog_ipconfig, null);
                builder.setView(dialog_ll);
                builder.setCancelable(true);
                TextView title = (TextView) dialog_ll
                        .findViewById(R.id.title);//设置标题
                final EditText entry_edt = (EditText) dialog_ll
                        .findViewById(R.id.et_entry_ip);//输入内容
                entry_edt.setText(SPUtils.getString("ipentry", ""));
                final EditText exit_edt = (EditText) dialog_ll
                        .findViewById(R.id.et_exit_ip);//输入内容
                exit_edt.setText(SPUtils.getString("ipexit", ""));
                Button btn_sure = (Button) dialog_ll.findViewById(R.id.dialog_btn_sure);
                Button btn_cancel = (Button) dialog_ll.findViewById(R.id.dialog_btn_cancel);
                final Dialog dialog = builder.create();
                dialog.show();
                btn_sure.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        ipentry = entry_edt.getText().toString();
                        SPUtils.putString("ipentry", ipentry);
                        ipexit = exit_edt.getText().toString();
                        SPUtils.putString("ipexit", ipexit);
                        Toast.makeText(context, "连接相机中...", 1).show();
                        Connect_onClick();
                        Connect_onClick2();

                    }
                });

                btn_cancel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        dialog.dismiss();
                    }
                });


                break;
            default:
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    /**
     * 合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    public Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
        if (background == null) {
            return null;
        }
        int screenWidth = context.getWindowManager().getDefaultDisplay().getWidth();
        int screenHeight = context.getWindowManager().getDefaultDisplay().getHeight();
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Bitmap newmap = Bitmap
                .createBitmap(bgWidth, bgHeight*2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, 0,
                screenHeight / 2, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newmap;
    }

    //  启动连接线程1
    int continuenext1 = -1;
    int connectnum1 = 0;

    public void Connect_onClick() {
        if (connectnum1 >= 1) {
            Toast.makeText(context, "已连接", Toast.LENGTH_SHORT).show();
            return;
        }
        int isconnect1 = camer1.FConnect(ipentry, this);
        if (isconnect1 != 1) {
            Toast.makeText(context, "进场摄像头连接失败", Toast.LENGTH_SHORT).show();
        }
        if (isconnect1 == 1) {

            Toast.makeText(context, "进场摄像头连接成功", Toast.LENGTH_SHORT).show();


            continuenext1 = 1;
            camer1.JosnOrBin();
            camer1.SetResu();
            camer1.MyThread();
            connectnum1++;
            EventBus.getDefault().post(new Event_Play_Camera(true));
        }

    }

    //启动连接线程2
    int continuenext2 = -1;
    int connectnum2 = 0;

    public void Connect_onClick2() {
        if (connectnum2 >= 1) {
            Toast.makeText(context, "已连接", Toast.LENGTH_SHORT).show();
            return;
        }
        int isconnect2 = camer2.FConnect(ipexit, this);
        if (isconnect2 != 1) {
            Toast.makeText(context, "出场摄像头连接失败", Toast.LENGTH_SHORT).show();
        }
        if (isconnect2 == 1) {
            Toast.makeText(context, "出场摄像头连接成功", Toast.LENGTH_SHORT).show();
            continuenext2 = 1;
            camer2.JosnOrBin();
            camer2.SetResu();
            camer2.MyThread();
            connectnum2++;
            EventBus.getDefault().post(new Event_Play_Camera(true));
        }

    }

    //抬杆1
    public void UP_Button() {
        if (continuenext1 != 1) {
            Toast.makeText(context, "请先连接", Toast.LENGTH_SHORT).show();
        }
        if (continuenext1 == 1) {
            try {
                camer1.Up_Button();
                addRecordList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //抬杆2
    public void UP_Button2() {
        if (continuenext2 != 1) {
            Toast.makeText(context, "请先连接", Toast.LENGTH_SHORT).show();
        }
        if (continuenext2 == 1) {
            try {
                camer2.Up_Button();
                addRecordList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //模拟触发1
    public void Trigger_Button() {
        if (continuenext1 != 1) {
            Toast.makeText(context, "请先连接", Toast.LENGTH_SHORT).show();
        }
        if (continuenext1 == 1) {
            try {
                camer1.Trigger_Button();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //模拟触发2
    public void Trigger_Button2() {
        if (continuenext2 != 1) {
            Toast.makeText(context, "请先连接", Toast.LENGTH_SHORT).show();
        }
        if (continuenext2 == 1) {
            try {
                camer2.Trigger_Button();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //断开1
    public void Disconnect1() {
        camer1.Disconnect();
        continuenext1 = -1;
        connectnum1 = 0;
        Toast.makeText(context, "已断开", Toast.LENGTH_SHORT).show();

    }

    //断开2
    public void Disconnect2() {
        camer2.Disconnect();
        continuenext2 = -1;
        connectnum2 = 0;
        Toast.makeText(context, "已断开", Toast.LENGTH_SHORT).show();
    }


    //////////////////////////////////////////////////////////////////以下为系统生成
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    //////////////////////////////////////////////////////////////////////////////////////////

    //显示识别结果图片
    public void show_ictrl(byte[] bb, String m_ip) {

        bitmap = BitmapFactory.decodeByteArray(bb, 0, bb.length);

        //image1.setImageBitmap(bitmap);
        String name = "192.168.1.55";
        if (m_ip.equals(name)) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    llCarInfo.setVisibility(View.VISIBLE);
                    mType = "entry";
                    entrybitmap = bitmap;
                    ivEntry.setImageBitmap(bitmap);
                }
            });
        }
        String name1 = "192.168.1.56";
        if (m_ip.equals(name1)) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    llCarInfo.setVisibility(View.VISIBLE);
                    mType = "exit";
                    ivExit.setImageBitmap(bitmap);
                    exitbitmap = bitmap;
                    if (entrybitmap != null) {
                        comparebitmap = combineBitmap(entrybitmap, exitbitmap);
                        ivCompare.setImageBitmap(comparebitmap);
                    }

                }
            });
        }

    }


    //可自行添加控件 显示识别结果文本
    public void show_text(byte[] bb, String m_ip) throws UnsupportedEncodingException {

        String s = new String(bb, "gbk");
        JSONObject Json = JSONObject.fromObject(s);
        if (Json.getInt("count") == 0) {

            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvFeeType.setText("无牌车");
                }
            });
            System.out.println("无牌车");
        } else {
            final String license = new String(Json.getJSONArray("item").getJSONObject(0).getString("license").getBytes("GBK"), "GBK");

            String name = ipentry;
            if (m_ip.equals(name)) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ACache.get(context).put("entry" + license, TimeUtil.getCurrentTime());
                        tvEntryTime.setText(TimeUtil.getCurrentTime());
                        mType = "entry";
                        tvCarNumber.setText(license);
                    }
                });
            }
            String name1 = ipexit;
            if (m_ip.equals(name1)) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvExitTime.setText(TimeUtil.getCurrentTime());
                        mType = "exit";
                        tvCarNumber.setText(license);

                        if (!TextUtils.isEmpty(ACache.get(context).getAsString("entry" + license))) {
                            tvParkTime.setText(TimeUtil.timeInterval(TimeUtil.getCurrentTime(),
                                    tvEntryTime.getText().toString()));
                            ACache.get(context).remove("entry" + license);

                        }
                    }
                });
            }
        }
    }
}
